<template>
  <n-config-provider :theme="theme">
    <n-global-style />
    <desktop />
    <applications />
  </n-config-provider>
</template>

<script setup lang="ts">
import { darkTheme, lightTheme, NConfigProvider, NGlobalStyle, useOsTheme } from "naive-ui"
import type { DebuggerEventExtraInfo } from "vue"
import { computed, onMounted, watch } from "vue"
import { useThemeStore } from "@/stores/theme"
import Desktop from "@/components/desktop/Desktop.vue"
import Applications from "./components/applications/Applications.vue"
import VariableName from "@/stores/theme/variable-name"
import ThemeTypes from "@/model/theme/types"

const themeStore = useThemeStore()

const themeType = themeStore.getVariableRef(VariableName.Theme.type)
const themeValue = themeStore.getVariableRef(VariableName.Theme.value)
const osThemeRef = useOsTheme()

watch(osThemeRef, () => {
  themeStore.setVariable(VariableName.Theme.value, osThemeRef.value === "dark" ? "dark" : "light")
})

const theme = computed(() => {
  if (themeType.value === "auto") {
    return themeValue.value === "dark" ? darkTheme : lightTheme
  } else {
    return themeType.value === "dark" ? darkTheme : lightTheme
  }
})

function changeTheme(key: string, value: string) {
  if (key === "--primary-color") {
    const color = ThemeTypes.Colors.get(value)
    if (!color) {
      return
    }
    darkTheme.common.primaryColor = color.value
    darkTheme.common.primaryColorHover = color.hover
    darkTheme.common.primaryColorPressed = color.pressed
    darkTheme.common.primaryColorSuppl = color.suppl
    lightTheme.common.primaryColor = color.value
    lightTheme.common.primaryColorHover = color.hover
    lightTheme.common.primaryColorPressed = color.pressed
    lightTheme.common.primaryColorSuppl = color.suppl
  }
}

//app加载时初始化样式变量
onMounted(() => {
  //初始化样式变量
  for (const [key, value] of themeStore.variables.entries()) {
    document.documentElement.style.setProperty(key, value)
    changeTheme(key, value)
  }
  //样式变量变化时进行修改
  themeStore.$subscribe((mutation) => {
    const events = mutation.events as DebuggerEventExtraInfo
    document.documentElement.style.setProperty(events.key, events.newValue)
    changeTheme(events.key, events.newValue)
  })
  //初始化主题
  if (themeType.value === "auto") {
    themeStore.setVariable(VariableName.Theme.value, osThemeRef.value === "dark" ? "dark" : "light")
  }
})
</script>

<style lang="scss">
#app {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
}
</style>
